package com.core.gui.dialogs;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JSeparator;
import javax.swing.JPasswordField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.core.dao.impl.ContactDAOImpl;
import com.core.dao.impl.UsernameDAOImpl;
import com.core.database.Manager;
import com.core.entities.Contact;
import com.core.entities.Username;
import com.core.exception.DAOException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLData;
import java.sql.SQLException;
import java.sql.SQLInput;
import java.sql.Statement;
import java.text.BreakIterator;
import java.util.Set;
import javax.swing.DropMode;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

public class RegistrationDialog extends JDialog {
	Contact contact = new Contact();
	ContactDAOImpl contactDAOImpl = new ContactDAOImpl();
	Username username = new Username();
	UsernameDAOImpl usernameDAOImpl = new UsernameDAOImpl();

	private final JPanel contentPanel = new JPanel();
	private final JLabel lblFirstName = new JLabel("First Name:*");
	private final JTextField firstNameTextField = new JTextField();
	private final JLabel lblSecondName = new JLabel("Second Name :");
	private final JTextField secondNameextField = new JTextField();
	private final JLabel lblLastName = new JLabel("Last Name :");
	private final JTextField lastNameTextField = new JTextField();
	private final JLabel lblMobileNumber = new JLabel("Mobile Number :");
	private final JTextField MobilPhoneTextField = new JTextField();
	private final JLabel lblEmail = new JLabel("E-Mail :");
	private final JTextField emailTextField = new JTextField();
	private final JSeparator separator = new JSeparator();
	private final JLabel lblUsername = new JLabel("Username :*");
	private final JTextField usernameTextField = new JTextField();
	private final JLabel lblPassword = new JLabel("Password :*");
	private final JPasswordField passwordField = new JPasswordField();
	private final JLabel lblRepassword = new JLabel("Re-Password :*");
	private final JPasswordField repasswordField = new JPasswordField();

	/**
	 * Launch the application.
	 */
//	public static void main(String[] args) {
//
//		try {
//
//			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//		} catch (UnsupportedLookAndFeelException e) {
//			// handle exception
//		} catch (ClassNotFoundException e) {
//			// handle exception
//		} catch (InstantiationException e) {
//			// handle exception
//		} catch (IllegalAccessException e) {
//			// handle exception
//		}
//		try {
//			RegistrationDialog dialog = new RegistrationDialog();
//			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
//			dialog.setVisible(true);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	/**
	 * Create the dialog.
	 */
	public RegistrationDialog() {
		usernameTextField.setBounds(75, 116, 170, 20);
		emailTextField.setBounds(50, 78, 271, 20);
		emailTextField.setColumns(10);
		MobilPhoneTextField.setBounds(90, 53, 148, 20);
		MobilPhoneTextField.setColumns(10);
		lastNameTextField.setBounds(398, 28, 86, 20);
		lastNameTextField.setColumns(10);
		secondNameextField.setBounds(240, 28, 86, 20);
		secondNameextField.setColumns(10);
		firstNameTextField.setBounds(73, 28, 86, 20);
		firstNameTextField.setColumns(10);
		setBounds(100, 100, 507, 266);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		lblFirstName.setBounds(10, 30, 65, 14);

		contentPanel.add(lblFirstName);

		contentPanel.add(firstNameTextField);
		lblSecondName.setBounds(166, 31, 72, 14);

		contentPanel.add(lblSecondName);

		contentPanel.add(secondNameextField);
		lblLastName.setBounds(336, 31, 57, 14);

		contentPanel.add(lblLastName);

		contentPanel.add(lastNameTextField);
		lblMobileNumber.setBounds(10, 56, 77, 14);

		contentPanel.add(lblMobileNumber);

		contentPanel.add(MobilPhoneTextField);
		lblEmail.setBounds(10, 81, 35, 14);

		contentPanel.add(lblEmail);

		contentPanel.add(emailTextField);
		separator.setBounds(10, 106, 474, 2);

		contentPanel.add(separator);
		lblUsername.setBounds(10, 119, 62, 14);

		contentPanel.add(lblUsername);

		contentPanel.add(usernameTextField);
		lblPassword.setBounds(10, 144, 60, 14);

		contentPanel.add(lblPassword);
		passwordField.setBounds(75, 141, 170, 20);

		contentPanel.add(passwordField);
		lblRepassword.setBounds(10, 169, 77, 14);

		contentPanel.add(lblRepassword);
		repasswordField.setBounds(90, 166, 155, 20);

		contentPanel.add(repasswordField);

		JLabel noteLabel = new JLabel(
				"Note : All fields have * it's important and cannt be null .");
		noteLabel.setBounds(10, 5, 265, 14);
		contentPanel.add(noteLabel);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						try {
							validatFields();
						} catch (DAOException | SQLException e1) {
							e1.printStackTrace();
						} catch (UnsupportedLookAndFeelException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}

	private void validatFields() throws UnsupportedLookAndFeelException,
			DAOException, SQLException {
		String miss = "Missing data of :" + "\n";
		if (firstNameTextField.getText().isEmpty()
				|| usernameTextField.getText().isEmpty()
				|| passwordField.getText().isEmpty()
				|| repasswordField.getText().isEmpty()) {

			if (firstNameTextField.getText().isEmpty()) {
				miss += "First Name.\n";
			}
			if (usernameTextField.getText().isEmpty()) {
				miss += "Username.\n";
			}
			if (passwordField.getText().isEmpty()) {
				miss += "Password.\n";
			}
			if (repasswordField.getText().isEmpty()) {
				miss += "Repeated Password.\n";
			}
			JOptionPane.showMessageDialog(null, miss, "",
					JOptionPane.ERROR_MESSAGE);

		} else {

			getData();
		}
	}

	public void getData() throws DAOException, SQLException {

		Connection connection = Manager.getConnection();
		int maxID = 0;
		Statement s2 = connection.createStatement();
		s2.execute("select max(ID) from username");
		ResultSet rs2 = s2.getResultSet();
		while (rs2.next()) {
			maxID = rs2.getInt(1);
		}
		contact.setFirst_name(firstNameTextField.getText());
		contact.setSecond_name(secondNameextField.getText());
		contact.setLast_name(lastNameTextField.getText());
		contact.setEmail(emailTextField.getText().toLowerCase());
		username.setUsername(usernameTextField.getText().toLowerCase());
		username.setPassword(passwordField.getText());
		if (passwordField.getText().equals(repasswordField.getText()) == false) {
			String string = "Password and repeated password is not match.";
			JOptionPane.showMessageDialog(null, string, "",
					JOptionPane.ERROR_MESSAGE);
		}
		{
			String stringRole = "admin";
			String sql = "SELECT role FROM username WHERE role = ?";
			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setString(1, stringRole);
			ResultSet rs = ps.executeQuery();

			boolean authenticated = false;
			if (rs.next()) {
				authenticated = true;
				username.setRole("user");
			} else {
				username.setRole("admin");
			}
			boolean userNameFound = userNameFound(usernameTextField.getText());
			if (userNameFound == true) {
				JOptionPane.showMessageDialog(null,
						"Username you enter is exist , Please enter other",
						null, JOptionPane.INFORMATION_MESSAGE);
			} else {
				usernameDAOImpl.insert(username);
				contact.setUsername_id(maxID + 1);
				contactDAOImpl.insert(contact);
				dispose();
				JOptionPane.showMessageDialog(null,
						"Complet registration successful", null,
						JOptionPane.INFORMATION_MESSAGE);
			}

		}

	}

	public boolean userNameFound(String name) {
		try {
			Connection connection = Manager.getConnection();
			Statement statement = connection.createStatement();
			String query = "select username from username";
			ResultSet rs = statement.executeQuery(query);
			while (rs.next()) {
				if (rs.getString(1).equalsIgnoreCase(name)) {
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
